import { cloneDeep } from 'lodash-es'
import { http } from '@/utils/http'
import { ElMessage } from 'element-plus'
import { getPlatformUser, getMoneyLimit } from '@/api/user'
import { checkRoles } from '@/stores/roles'
import { initiaStore } from '@/stores/initialization.js'
import _ from 'lodash-es'


export const myAmbientStore = () => {
    const userStore = useUserStore()
    const router = useRouter()
    const initiaStores = initiaStore()
    const state = reactive({
        activeMenu: 'recentlyOpened',
        filterDrawer: {
            show: false
        },
        detailDrawer: {
            show: false,
            data: {}
        },
        pageData: {
            total: 0,
            page: 1,
            page_size: 20
        },
        listLoading: false,
        environmentList: [],


        formData_copy: {},
        map: {},
        filterCondition: {
            type: 0,
            value: ''
        },
        filterCondition2: {},
        sortRole: '-open_time',

        dialogData: {},
        numberDialog: {
            show: false
        },
        nameDialog: {
            show: false
        },
        ipDialog: {
            show: false
        },
        quoteipDialog: {
            show: false
        },
        remarkDialog: {
            show: false
        },
        plantuserDialog: {
            show: false
        },
        cookieDialog: {
            show: false
        },
        downloadDialog: {
            show: false
        },

        sortRoleMap: [
            {
                value: 'number',
                label: '序号正序'
            }, {
                value: '-number',
                label: '序号倒序'
            }, {
                value: 'id',
                label: '环境编号正序'
            }, {
                value: '-id',
                label: '环境编号倒序'
            }, {
                value: 'created_at',
                label: '创建时间正序'
            }, {
                value: '-created_at',
                label: '创建时间倒序'
            }, {
                value: 'open_time',
                label: '打开时间正序'
            }, {
                value: '-open_time',
                label: '打开时间倒序'
            }, {
                value: 'name',
                label: '环境名称正序'
            }, {
                value: '-name',
                label: '环境名称倒叙'
            },
        ],

        filterSelect: [
            {
                value: 0,
                label: '环境',
                field: 'name'
            }, {
                value: 1,
                label: '序号',
                field: 'number'
            }, {
                value: 2,
                label: '环境编号',
                field: 'id'
            }, {
                value: 3,
                label: 'ip',
                field: 'ip'
            }, {
                value: 4,
                label: '账号',
                field: 'account'
            }, {
                value: 5,
                label: '账号名称',
                field: 'user_name'
            }, {
                value: 6,
                label: '备注',
                field: 'remark'
            },
        ],
    })

    const openambientAdd = () => {
        // let maxNumber = state.environmentList.length > 0 ? '' : 1
        router.replace({
            name: 'ambientAdd',
            query: { id: '', manager: 'recentlyOpened' } // 使用查询参数传递
        });
    }

    const editEnvironment = (row) => {
        router.replace({
            name: 'ambientAdd',
            query: { id: row.id, manager: 'recentlyOpened' } // 使用查询参数传递
        });
    }

    const getEnvironmentList = () => {
        state.listLoading = true
        let params = {
            page: state.pageData.page,
            page_size: state.pageData.page_size,
            state: 0,
            is_open: 1
        }

        if (state.filterCondition.value != '') {
            state.filterSelect.forEach(item => {
                if (item.value == state.filterCondition.type) {
                    params[item.field] = state.filterCondition.value
                }
            });
        }

        Object.entries(state.filterCondition2).forEach(([key, value]) => {
            if (key != 'creat_time') {
                if (typeof value === 'string') {
                    if (value != '') {
                        params[key] = value
                    }
                } else if (Array.isArray(value)) {
                    if (value.length > 0) {
                        params[key] = value.join(',')
                    }
                }
            } else {
                if (value.length == 2 && value[0] != '') {
                    params.creat_begin_time = value[0]
                    params.creat_end_time = value[1]
                }
            }
        });

        params.sort_type = state.sortRole
        http.get('/environment/get_environments', { params }).then((res) => {
            state.listLoading = false
            state.environmentList = res.data.list

            state.pageData.total = res.data.total
            state.pageData.page = res.data.page
            state.pageData.page_size = res.data.page_size
        }).catch(() => {
            state.listLoading = false

            state.environmentList = []

            state.pageData.total = 0
            state.pageData.page = 1
            state.pageData.page_size = 20
        })
    }

    const getOptionsLabel = (value, options) => {
        let label = ''
        options.forEach(item => {
            if (value == item.value) {
                label = item.label
            }
        });
        return label
    }

    // 获取平台
    const getPlatforms = () => {
        http.get('/environment/get_platforms').then(res => {
            state.map.bc_types = res.data.list.map(item => {
                return {
                    value: item.id,
                    label: item.platform_name
                }
            })
        })
    }

    // 获取分组
    const getGroupList = () => {
        http.get(`/environment/get_groups?page=1&page_size=9999`).then(res => {
            state.map.groupList = res.data.list.map(item => {
                return {
                    value: item.id,
                    label: item.name
                }
            })
        })
    }

    // 获取语言
    const getLanguages = () => {
        http.get('/environment/get_languages').then(res => {
            state.map.languages = res.data.list.map(item => {
                return {
                    value: item.language_code,
                    label: item.language_name
                }
            })
        })
    }

    const getcommon = (row, num) => {
        console.log(row);
        let body = {
            is_in_common_use: num,
            environment_id: row.id
        }
        http.put('/environment/update_environment_common', body).then((res) => {
            ElMessage({
                message: '设置成功',
                type: 'success',
            })
        })

    }

    const getdelete = (row) => {
        http.delete(`/environment/delete_environment?id=${row.id}`).then((res) => {
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            getEnvironmentList()
        })
    }

    onMounted(() => {
        state.map = initiaStores.initiaData.map
        state.formData_copy = initiaStores.initiaData.formData_copy
        initData()
    })

    const initData = () => {
        getEnvironmentList()
        getPlatforms()
        getGroupList()
        getLanguages()
    }

    onUnmounted(() => {

    })

    return {
        state,

        openambientAdd,
        getEnvironmentList,
        editEnvironment,
        getOptionsLabel,
        getcommon,
        getdelete,
        getLanguages

    }
}
